import logging
from preprocessor.dwc.model_router import ACCOUNT_MODEL_ROUTER as DWC_ACCOUNT_MODEL_ROUTER
from preprocessor.cp.model_router import ACCOUNT_MODEL_ROUTER as CP_ACCOUNT_MODEL_ROUTER
from common.utils.db import list_object

_LOGGER = logging.getLogger(__name__)

ACCOUNT_TABLE_ROUTER = dict()
ACCOUNT_TABLE_ROUTER.update(DWC_ACCOUNT_MODEL_ROUTER)
ACCOUNT_TABLE_ROUTER.update(CP_ACCOUNT_MODEL_ROUTER)


def get_user(platform_id, user_id):
    table = ACCOUNT_TABLE_ROUTER[platform_id]
    user = table.objects.filter(user_id=user_id).first()
    if user:
        user = user.__dict__
        user.pop('_state')
    return user if user else {}


def list_user(platform_id, query_dct, disable_paginate=False):
    table = ACCOUNT_TABLE_ROUTER[platform_id]
    return list_object(query_dct, table, disable_paginate=disable_paginate)


def get_target_user_id_pool(platform_id, query_dct,):
    table = ACCOUNT_TABLE_ROUTER[platform_id]
    accounts = list_object(query_dct, table, disable_paginate=True, get_field='user_id')
    return [account for account in accounts]


def get_distinct_channel(merchant_name):
    table = ACCOUNT_TABLE_ROUTER[merchant_name]
    distinct_channel_list = table.objects.values('channel').distinct()
    ret = []
    for item in distinct_channel_list:
        ret.append(item['channel'])
    if "" in ret:
        ret.remove("")
    return ret


def get_distinct_channel_exists_app_id(merchant_name):
    table = ACCOUNT_TABLE_ROUTER[merchant_name]
    distinct_channel_list = table.objects.filter(extra_info__isnull=False).values('channel').distinct()
    ret = []
    for item in distinct_channel_list:
        ret.append(item['channel'])
    if "" in ret:
        ret.remove("")
    return ret